<template>
	<view class="content">
		<cusHeaderVue titleContent="任务反馈" :showBack="true"></cusHeaderVue>
		<scroll-view scroll-y="true"
			:style="{paddingTop: `calc(${scrollerHeight} + 90rpx)`,height: `calc(100vh - ${scrollerHeight} - 90rpx`}">
			<view class="contBox">
				<view class="personBox">
					<view class="approvalTit">
						反馈内容
					</view>
					<view class="approvaltextarea">
						<textarea v-model="feedbackData.description" placeholder="请输入反馈内容" placeholder-style="color: #5A5964;"></textarea>
					</view>
				</view>
				
				<view class="personBox">
					<view class="approvalTit">
						反馈照片
					</view>
					<view class="popupImg">
						<!-- 已上传的图片列表 -->
						<view v-for="(image, index) in feedbackData.imageList" :key="index" class="popupImgLi">
							<image :src="image" mode="aspectFill" @click="previewImage(index)"></image>
							<view class="delete-icon" @click.stop="deleteImage(index)">×</view>
						</view>
						<!-- 添加图片按钮 -->
						<view v-if="feedbackData.imageList.length < 9" class="popupImgLi addBtn" @click="chooseImage">
							<image src="/static/home/zhaopikan.png" mode=""></image>
						</view>
					</view>
				</view>
				
				<view class="personBox">
					<view class="approvalTit">
						附件
					</view>
					<view class="popupAnnex">
						<view class="popupAnnexBtn" @click="chooseFile">
							选择文件
						</view>
						<span v-if="feedbackData.fileName">{{ feedbackData.fileName }}</span>
						<span v-else>未选择任何文件</span>
					</view>
				</view>
				
			</view>
		</scroll-view>
		<view class="btnBox">
			<view class="btnLi" @click="submitFeedback" :class="{ disabled: isSubmitting }">
				{{ isSubmitting ? '提交中...' : '确认提交' }}
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		onLoad,
	} from '@dcloudio/uni-app';
	import {
		ref
	} from 'vue';
	import cusHeaderVue from '@/components/cus-header.vue';
	import { uploadImage,uploadFile } from '@/api/interface.js';
import BASE_URL from '@/utils/env.js';
	const scrollerHeight = ref('');
	
	// 任务数据
	const currentTaskData = ref({});
	
	// 反馈数据
	const feedbackData = ref({
		id: '', // 任务ID
		description: '', // 反馈内容
		fileUrl: '', // 附件地址
		imageList: [], // 图片列表（本地路径）
		imagePath: '', // 图片地址（服务器路径，逗号分隔）
		fileName: '', // 附件名称
		taskFile: '' // 任务文件（如果有）
	});
	
	// 提交状态
	const isSubmitting = ref(false);

	//获取状态栏高度
	const getBarHeight = () => {
		uni.getSystemInfo({
			success: function(res) {
				scrollerHeight.value = res.statusBarHeight + 'px'
			}
		});
	}

	// 选择图片
	const chooseImage = async () => {
		try {
			const res = await uni.chooseImage({
				count: 9 - feedbackData.value.imageList.length,
				sizeType: ['original', 'compressed'],
				sourceType: ['album', 'camera']
			});
			
			// 添加到图片列表
			feedbackData.value.imageList.push(...res.tempFilePaths);
		} catch (error) {
			console.error('选择图片失败:', error);
		}
	}
	
	// 预览图片
	const previewImage = (index) => {
		uni.previewImage({
			current: feedbackData.value.imageList[index],
			urls: feedbackData.value.imageList,
			success: function(res) {
				console.log('预览图片成功:', res);
			},
			fail: function(error) {
				console.error('预览图片失败:', error);
			}
		});
	}
	
	// 删除图片
	const deleteImage = (index) => {
		// 弹出确认对话框
		uni.showModal({
			title: '确认删除',
			content: '确定要删除这张图片吗？',
			confirmText: '确定',
			cancelText: '取消',
			success: (res) => {
				if (res.confirm) {
					// 执行删除操作
					feedbackData.value.imageList.splice(index, 1);
					uni.showToast({
						title: '删除成功',
						icon: 'success',
						duration: 1500
					});
				}
			}
		});
	}
	
	// 选择文件
	const chooseFile = async () => {
		try {
			const res = await uni.chooseMessageFile({
				count: 1,
				type: 'file',
				extraFileTypes: ['doc', 'docx', 'pdf', 'xlsx', 'xls', 'ppt', 'pptx']
			});
			
			if (res.tempFiles && res.tempFiles.length > 0) {
				const file = res.tempFiles[0];
				feedbackData.value.fileName = file.name;
				// 选择文件后立即上传
				await uploadTaskFile(file.path, file.name);
			}
		} catch (error) {
			console.error('选择文件失败:', error);
			uni.showToast({
				title: '选择文件失败，请重试',
				icon: 'none'
			});
		}
	}
	
	// 上传单张图片
	const uploadSingleImage = async (filePath) => {
		try {
			// 直接使用导入的uploadImage接口
			const result = await uploadImage(filePath, 'task');
			let url = result.url;
			// 确保URL被正确处理，去除可能存在的引号和空格
			if (typeof url === 'string') {
				url = url.trim();
				// 去除可能存在的前后单引号或双引号
				if ((url.startsWith('"') && url.endsWith('"')) || (url.startsWith('\'') && url.endsWith('\''))) {
					url = url.substring(1, url.length - 1);
				}
			}
			return url;
		} catch (error) {
			console.error('上传图片失败:', error);
			throw error;
		}
	}
	
	// 上传任务文件
	const uploadTaskFile = async (filePath, fileName) => {
		try {
			isSubmitting.value = true;
			uni.showLoading({
				title: '文件上传中...'
			});
			
			// 直接使用uni.uploadFile API，这是小程序环境中最可靠的文件上传方式
			const uploadResult = await new Promise((resolve, reject) => {
				uni.uploadFile({
						url: BASE_URL + 'infra/file/upload', // 使用完整的URL路径
						filePath: filePath,
						name: 'file',
						formData: {
							type: 'task'
						},
						header: {
							'Authorization': uni.getStorageSync('token') || '',
							'Content-Type': 'multipart/form-data'
						},
					success: (uploadFileRes) => {
						try {
							const data = JSON.parse(uploadFileRes.data);
							if (uploadFileRes.statusCode === 200 && data.code === 0) {
								resolve(data); // 返回完整的data对象
							} else {
								reject(new Error(data.message || '上传失败'));
							}
						} catch (e) {
							console.error('响应解析错误:', uploadFileRes.data);
							reject(new Error('解析响应失败: ' + e.message));
						}
					},
					fail: (error) => {
						console.error('上传请求失败:', error);
						reject(error);
					}
				});
			});
			
			// 确保URL被正确处理，去除可能存在的引号或其他不必要的字符
			let url = uploadResult.data;
			// 去除前后可能存在的引号和空格
			if (typeof url === 'string') {
				url = url.trim();
				// 去除可能存在的前后单引号或双引号
				if ((url.startsWith('"') && url.endsWith('"')) || (url.startsWith('\'') && url.endsWith('\''))) {
					url = url.substring(1, url.length - 1);
				}
			}
			feedbackData.value.fileUrl = url;
			
			uni.hideLoading();
			uni.showToast({
				title: '文件上传成功',
				icon: 'success'
			});
		} catch (error) {
			console.error('上传文件失败:', error);
			uni.hideLoading();
			uni.showToast({
				title: '文件上传失败，请重试',
				icon: 'none'
			});
			throw error;
		} finally {
			isSubmitting.value = false;
		}
	}
	
	// 提交反馈
	const submitFeedback = async () => {
		// 表单验证
		if (!feedbackData.value.description.trim()) {
			uni.showToast({
				title: '请输入反馈内容',
				icon: 'none'
			});
			return;
		}
		
		if (feedbackData.value.imageList.length === 0) {
			uni.showToast({
				title: '请至少上传一张反馈照片',
				icon: 'none'
			});
			return;
		}
		
		// 如果选择了文件但还没有上传成功
		if (feedbackData.value.fileName && !feedbackData.value.fileUrl) {
			uni.showToast({
				title: '文件尚未上传成功，请重试',
				icon: 'none'
			});
			return;
		}
		
		isSubmitting.value = true;
		uni.showLoading({
			title: '提交中...'
		});
		
		try {
			// 判断哪些图片需要上传（本地图片路径和临时文件路径需要上传，只有服务器返回的远程URL不需要）
			const uploadPromises = feedbackData.value.imageList.map(async (filePath) => {
				// 检查是否是远程URL（以http/https开头）但排除临时文件路径（http://tmp/）
				if (filePath.startsWith('http://') || filePath.startsWith('https://')) {
					// 小程序临时文件路径需要上传
					if (filePath.startsWith('http://tmp/')) {
						return await uploadSingleImage(filePath);
					} else {
						return filePath; // 已经是服务器地址，直接返回
					}
				} else {
					return await uploadSingleImage(filePath); // 本地图片需要上传
				}
			});
			
			const imageUrls = await Promise.all(uploadPromises);
			
			// 构建提交数据
			const submitData = {
				id: uni.getStorageSync('currentTaskData').id || '',
				description: feedbackData.value.description,
				fileUrl: feedbackData.value.fileUrl || '',
				imagePath: imageUrls.join(','),
				fileName: feedbackData.value.fileName || ''
			};
			
			// 保存当前反馈数据用于可能的回显
			uni.setStorageSync('savedFeedbackData_' + feedbackData.value.id, {
				imagePath: submitData.imagePath,
				description: submitData.description,
				fileName: submitData.fileName,
				fileUrl: submitData.fileUrl
			});
			console.log(submitData)
			console.log(submitData)
			console.log(submitData)
			
			// 调用提交接口
			const res = await submitTaskFeedback(submitData);
			
			uni.hideLoading();
			if (res.code === 0) {
				uni.showToast({
					title: '提交成功',
					icon: 'success'
				});
				// 跳转到反馈成功页，由成功页倒计时后进入我的任务（已完成）
				uni.navigateTo({
					url: '/pages/mine/taskFeedbackSuccess?delay=3'
				});
			} else {
				uni.showToast({
					title: res.message || '提交失败',
					icon: 'none'
				});
			}
		} catch (error) {
			uni.hideLoading();
			console.error('提交反馈失败:', error);
			uni.showToast({
				title: '提交失败，请重试',
				icon: 'none'
			});
		} finally {
			isSubmitting.value = false;
		}
	}
	
	// 提交任务反馈接口
	const submitTaskFeedback = (data) => {
		return new Promise((resolve, reject) => {
			uni.request({
				url: BASE_URL + 'system/dx-task-feedback/update',
				method: 'PUT',
				header: {
					'content-type': 'application/json',
					'Authorization': uni.getStorageSync('token') || ''
				},
				data: data,
				success: (res) => {
					resolve(res.data);
				},
				fail: (err) => {
					reject(err);
				}
			});
		});
	}

	// 从本地存储获取任务数据
	const loadTaskData = () => {
		try {
			const taskData = uni.getStorageSync('currentTaskData');
			console.log(taskData)
			console.log(taskData)
			console.log(taskData['id'])
			console.log(taskData['id'])
			if (taskData) {
				currentTaskData.value = taskData;
				// 设置任务ID
				feedbackData.value.id = taskData.id  || '';
				
				// 如果有已保存的反馈数据，加载之前上传的图片
				const savedFeedbackData = uni.getStorageSync('savedFeedbackData_' + feedbackData.value.id);
				if (savedFeedbackData) {
					// 加载已上传的图片（用于修改时的回显）
					if (savedFeedbackData.imagePath) {
						// 从服务器路径转换为可预览的图片列表
						feedbackData.value.imageList = savedFeedbackData.imagePath.split(',').filter(url => url.trim());
					}
					// 加载其他反馈数据
					if (savedFeedbackData.description) {
						feedbackData.value.description = savedFeedbackData.description;
					}
					if (savedFeedbackData.fileName) {
						feedbackData.value.fileName = savedFeedbackData.fileName;
						feedbackData.value.fileUrl = savedFeedbackData.fileUrl;
					}
				}
			}
		} catch (error) {
			console.error('加载任务数据失败:', error);
		}
	}

	onLoad(() => {
		getBarHeight();
		loadTaskData();
	})
</script>

<style lang="scss" scoped>
	.content {
		width: 100%;
		height: 100vh;
		background: #ffffff;
	}

	.bgColor {
		width: 100%;
		height: 740rpx;
		position: absolute;
		z-index: -1;
		top: 0;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.contBox {
		padding: 22rpx 40rpx;
		box-sizing: border-box;
		padding-bottom: calc(env(safe-area-inset-bottom) + 101rpx);
		.personBox {
			width: 100%;
			border-radius: 12.82rpx 12.82rpx 12.82rpx 12.82rpx;
			background: #ffffff;
			margin-bottom: 46rpx;
			.approvalTit {
				font-weight: 500;
				font-size: 33.33rpx;
				color: #1C2027;
				margin-bottom: 23rpx;
			}
			.popupAnnex{
				margin-top: 25rpx;
				font-size: 24.36rpx;
				font-weight: 400;
				color: #7F8494;
				display: flex;
				align-items: center;
				.popupAnnexBtn{
					width: 173.08rpx;
					height: 61.54rpx;
					border-radius: 10.26rpx 10.26rpx 10.26rpx 10.26rpx;
					background: #f4f6f991;
					font-size: 24.36rpx;
					font-weight: 400;
					color: #222222;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}
			.approvaltextarea{
				width: 100%;
				border-radius: 10.26rpx 10.26rpx 10.26rpx 10.26rpx;
				background: #f4f6f991;
				padding: 19rpx;
				box-sizing: border-box;
				border: 1px solid #eaecf1;
				textarea {
					font-weight: 400;
					width: 100%;
					height: 200rpx;
					font-size: 24.36rpx;
					font-weight: 400;
					color: #7F8494;
				}
			}

			.popupImg {
						display: flex;
						flex-wrap: wrap;
						gap: 20rpx;
						.popupImgLi {
							margin-top: 21rpx;
							width: 196.15rpx;
							height: 196.15rpx;
							border-radius: 10.26rpx 10.26rpx 10.26rpx 10.26rpx;
							background: #f4f6f991;
							display: flex;
							align-items: center;
							justify-content: center;
							border: 1px solid #eaecf1;
							position: relative;
							image {
								width: 130rpx;
								height: 130rpx;
								border-radius: 10.26rpx;
							}
							/* 缩小添加照片按钮的相机图标 */
							.addBtn image{
								width: 62.82rpx;
								height: 45.51rpx;
							}
							.delete-icon {
								position: absolute;
								top: -10rpx;
								right: -10rpx;
								width: 40rpx;
								height: 40rpx;
								border-radius: 50%;
								background: #ff4d4f;
								color: white;
								font-size: 36rpx;
								display: flex;
								align-items: center;
								justify-content: center;
								font-weight: bold;
							}
						}
					}

			
		}





	}

	.btnBox {
		display: flex;
		align-items: center;
		justify-content: center;
		position: fixed;
		// bottom: calc(env(safe-area-inset-bottom) + 20rpx);
		bottom: 0;
		width: 100%;
		left: 0;
		padding: 20rpx 55rpx calc(env(safe-area-inset-bottom) + 20rpx);
		box-sizing: border-box;
		background: #ffffff;

		.btnLi {
			height: 80rpx;
			border-radius: 40.38rpx 40.38rpx 40.38rpx 40.38rpx;
			background: linear-gradient(-90deg, #feaf38, #f98434);
			box-shadow: 0 3.85rpx 4.49rpx 0 #f984344d;
			color: #ffffff;
			width: 512.82rpx;
			
			font-size: 32.05rpx;
			font-weight: 400;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		
	}
</style>